/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ModeloLogicoSistema.AdministradorOrden;
import ModeloLogicoSistema.AdministradorStock;
import ModeloLogicoSistema.Orden;
import java.awt.Color;
import java.awt.Component;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author debo
 */
public class Contabilidad extends javax.swing.JDialog {

    /**
     * Creates new form Contabilidad
     */
    private AdministradorOrden adm;
    private AdministradorStock administradorStock;
    private ArrayList<Orden> ordenes;
    private Calendar calendario = new GregorianCalendar();
    SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
    
    public Contabilidad(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        
        try {
            this.adm=new AdministradorOrden();
            this.administradorStock=new AdministradorStock();
        } catch (SQLException ex) {
            Logger.getLogger(Contabilidad.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        cargarTablaIngresos();
        this.setVisible(true);
    }
    
    public void cargarTablaIngresos(){
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        selectorFechaInicial = new com.toedter.calendar.JDateChooser();
        selectorFechaFinal = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaEgresos = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tablaIngresos = new javax.swing.JTable();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaTotales = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Informe Contabilidad");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        jButton1.setText("Cerrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        selectorFechaInicial.setDateFormatString("dd/MM/yyyy");
        Calendar c1 = GregorianCalendar.getInstance();
        c1.add(Calendar.DATE, -31);
        this.selectorFechaInicial.setDate(c1.getTime());

        selectorFechaFinal.setDateFormatString("dd/MM/yyyy");
        Date fecha=Calendar.getInstance().getTime();
        this.selectorFechaFinal.setDate(fecha);

        jLabel3.setText("Fecha Inicio");

        jLabel4.setText("Fecha Fin");

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/ver.png"))); // NOI18N
        jButton2.setText("Ver");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel5.setText("Ingresos");

        tablaEgresos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro Ingreso Stock", "Fecha", "Monto"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaEgresos.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tablaEgresos);

        jLabel6.setText("Egresos");

        tablaIngresos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "IdOrden", "Fecha", "Monto", "Costos", "Monto Final"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaIngresos.getTableHeader().setReorderingAllowed(false);
        jScrollPane3.setViewportView(tablaIngresos);

        tablaTotales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Subtotal Ingresos", "Subtotal Egresos", "Saldo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaTotales.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaTotales);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(selectorFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(selectorFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(24, 24, 24)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(93, 93, 93)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(223, 223, 223)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(selectorFechaInicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(selectorFechaFinal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(17, 17, 17)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String fechaI,fechaF;
        Double subtotalIng=new Double(0),subtotalEg=new Double(0);
        try{
            DefaultTableModel modelo=(DefaultTableModel) this.tablaIngresos.getModel();
            DefaultTableModel modeloEgresos=(DefaultTableModel) this.tablaEgresos.getModel();
            if(modelo.getRowCount()!=0 | modeloEgresos.getRowCount()!=0){
                int filas=tablaIngresos.getRowCount();
	        for (int i = 0;filas>i; i++) {
                    modelo.removeRow(0);
	        }
                filas=tablaEgresos.getRowCount();
	        for (int i = 0;filas>i; i++) {
                    modeloEgresos.removeRow(0);
	        }

            }
            Date fecha = this.selectorFechaInicial.getDate();
            calendario.setTime(fecha);
            fechaI= formateador.format(calendario.getTime());
            fecha=this.selectorFechaFinal.getDate();
            calendario.setTime(fecha);
            fechaF=formateador.format(calendario.getTime());
            this.ordenes=adm.buscarOrdenesEntregadasEntreLosDias(fechaI,fechaF);
            for(Orden orden: ordenes){
                Integer codigo=orden.getCodOrden();
                String fechaE=orden.getFechaEntrega();
                Double costos=evaluarCostosPorServicios(orden);
                Double descuento=orden.getDescuento();
                Double monto=orden.getMontoTotal()-descuento;
                Double montoT=monto-costos;
                Object[] ingreso={codigo,fechaE,monto,costos,montoT};
                modelo.addRow(ingreso);  
                subtotalIng=subtotalIng+montoT;
            }
            for(Object[] datos:this.administradorStock.getIngresosEntreFechas(fechaI, fechaF)){
                Integer precio=2;
                modeloEgresos.addRow(datos);
                subtotalEg=subtotalEg+(Double)datos[precio];
            }
            this.tablaTotales.setValueAt(subtotalIng, 0, 0);
            this.tablaTotales.setValueAt(subtotalEg, 0, 1);
            Double total=subtotalIng-subtotalEg;
            if(total>0){
                this.configurarColumnaTotal(true);
                //this.tablaTotales.setForeground(Color.GREEN);
            }
            else{
                this.configurarColumnaTotal(false);
            }
            this.tablaTotales.setValueAt(Math.rint(total), 0, 2);                                                     
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Debe seleccionar fechas", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
  //  public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
    /*    try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Contabilidad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
      /*  java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Contabilidad dialog = new Contabilidad(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private com.toedter.calendar.JDateChooser selectorFechaFinal;
    private com.toedter.calendar.JDateChooser selectorFechaInicial;
    private javax.swing.JTable tablaEgresos;
    private javax.swing.JTable tablaIngresos;
    private javax.swing.JTable tablaTotales;
    // End of variables declaration//GEN-END:variables

    private Double evaluarCostosPorServicios(Orden orden) {
        Double costo;
        try{
            costo=this.adm.getCostoTercerizados(orden.getCodOrden());
        }catch(Exception e){
            costo=new Double(0);
        }
        return costo;
    }
    
  
    private void configurarColumnaTotal(final Boolean esPositivo){
            
            TableCellRenderer render = new TableCellRenderer() {
            @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                        JLabel lbl = new JLabel(value == null? "": value.toString());
                        lbl.setHorizontalAlignment(SwingConstants.RIGHT);
                        
                if(esPositivo)
                    lbl.setForeground(Color.GREEN);  //fuente verde
                else{
                    lbl.setForeground(Color.red);
                }
                return lbl;
            
                }    
        };
           
        this.tablaTotales.getColumnModel().getColumn(2).setCellRenderer(render);
    }
}
